package com.cykj.user.service.impl;

import com.cykj.common.core.domain.R;

import com.cykj.common.redis.service.RedisService;
import com.cykj.system.api.RemoteShopService;
import com.cykj.user.domain.History;
import com.cykj.user.domain.Store;
import com.cykj.user.mapper.HistoryMapper;

import com.cykj.user.mapper.StoreMapper;
import com.cykj.user.service.IHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HistoryServiceImpl implements IHistoryService {

    @Autowired
    private HistoryMapper historyMapper;


    @Autowired
    private RedisService redisService;

    private static final String HISTORY_PREFIX = "history:";
    private static final long CACHE_EXPIRE = 10000; // 过期时间(分钟)
    private static final long RANDOM_OFFSET = new Random().nextInt(60); // 随机偏移量（0~60分钟）防止雪崩
    @Override
    @Transactional
    public int addBrowseHistory(Long businessId, Long customerId) {
        // 检查是否已有记录
        History exist = historyMapper.selectByBusinessAndCustomer(businessId, customerId);
        int result;

        if (exist != null) {
            // 更新浏览时间
            exist.setCreateTime(new Date());
            exist.setBrowseStatus(1);
            result = historyMapper.updateHistory(exist);
        } else {
            // 新增记录
            History history = new History();
            history.setBusinessId(businessId);
            history.setCustomerId(customerId);
            history.setCreateTime(new Date());
            history.setBrowseStatus(1);
            result = historyMapper.insertHistory(history);
        }

        // 增量更新
        incrementUpdateBrowseHistoryCache(businessId, customerId);
        return result;
    }

    @Override
    public List<History> getBrowseHistory(Long customerId) {
        String cacheKey = HISTORY_PREFIX + customerId;

        // 从Redis Hash获取数据
        Map<String, History> historyMap = redisService.getCacheMap(cacheKey);

        if (historyMap == null || historyMap.isEmpty()) {
            // 缓存未命中，全量重建
            updateBrowseHistoryCache(customerId);
            historyMap = redisService.getCacheMap(cacheKey);
        }

        // 转换为List并按时间排序
        return historyMap.values().stream()
                .sorted((h1, h2) -> h2.getCreateTime().compareTo(h1.getCreateTime()))
                .collect(Collectors.toList());
    }

    private void updateBrowseHistoryCache(Long customerId) {
        String cacheKey = HISTORY_PREFIX + customerId;
        List<History> historyList = historyMapper.selectByCustomerId(customerId);
        Map<String, History> historyMap = historyList.stream()
                .collect(Collectors.toMap(
                        h -> String.valueOf(h.getBusinessId()),
                        h -> h,
                        (oldVal, newVal) -> oldVal.getCreateTime().after(newVal.getCreateTime()) ? oldVal : newVal
                ));
        redisService.setCacheMap(cacheKey, historyMap);
        redisService.expire(cacheKey, CACHE_EXPIRE + RANDOM_OFFSET, TimeUnit.MINUTES);
    }

    private void incrementUpdateBrowseHistoryCache(Long businessId, Long customerId) {
        String cacheKey = HISTORY_PREFIX + customerId;
        // 查询最新记录
        History latestHistory = historyMapper.selectByBusinessAndCustomerWithShop(businessId, customerId);
        if (latestHistory == null) {
            return;
        }

        redisService.setCacheMapValue(cacheKey, String.valueOf(businessId), latestHistory);
        // 设置随机过期时间
        redisService.expire(cacheKey, CACHE_EXPIRE + RANDOM_OFFSET, TimeUnit.MINUTES);

    }


    @Override
    @Transactional
    public int deleteBrowseHistory(Long browseId) {
        History history = historyMapper.selectById(browseId);
        if (history == null || history.getBrowseStatus() == 0) {
            return 0;
        }

        //逻辑删除数据库记录
        int result = historyMapper.deleteHistory(browseId);

        if (result > 0) {
            removeFromBrowseHistoryCache(history.getBusinessId(), history.getCustomerId());
        }

        return result;
    }

    /**
     * 从缓存Hash中移除指定记录
     */
    private void removeFromBrowseHistoryCache(Long businessId, Long customerId) {
        String cacheKey = HISTORY_PREFIX + customerId;
        redisService.deleteCacheMapValue(cacheKey, String.valueOf(businessId));
    }



}